<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="链路ID" prop="traceId">
        <el-input
          style="width:295px;"
          v-model="queryParams.traceId"
          placeholder="链路ID,仅支持精确查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单名称" prop="workOrderName">
        <el-input
          style="width:295px;"
          v-model="queryParams.workOrderName"
          placeholder="工单名称,支持模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="脚本名称" prop="repairApiName">
        <el-input
          style="width:295px;"
          v-model="queryParams.repairApiName"
          placeholder="脚本名称,支持模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="workOrderStatus">
        <el-select
          style="width:295px;"
          v-model="queryParams.workOrderStatus"
          placeholder="请选择工单状态,支持多选"
          clearable
          filterable
          multiple
          @change="val => handleStoreQueryParams(storeStatusKey, val)"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="display: flex; align-items: center;">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          style="color: red;"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hawk-eye:repair-work-order:remove']"
        >删除
        </el-button>
      </el-col>
      <div style="margin-left: auto;">
        <el-link
          style="font-size: 13px; color: blue;"
          :underline="false"
          @click="handleDoc">
          什么是修复工单？
        </el-link>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairWorkOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="工单名称" align="center" prop="workOrderName">
        <template #default="scope">
          <el-tooltip content="点击跳转至告警日志" placement="top">
                <span style="color: #1890ff; cursor: pointer;" @click="handleLogLabel(scope.row)">
                  {{ scope.row.workOrderName }}
                </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="待执行脚本" align="center" prop="repairApiName" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-tooltip content="点击跳转至修复脚本" placement="top">
                <span style="color: #1890ff; cursor: pointer;" @click="handleRepairLabel(scope.row)">
                  {{ scope.row.repairApiName }}
                </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="当前审批人" align="center" prop="nodeUserName"/>
      <el-table-column label="状态" align="center" prop="statusText">
      <template slot-scope="scope">
        <el-tag v-if="scope.row.status === '0'"  effect="plain">待审核</el-tag>
        <el-tag v-else-if="scope.row.status === '1'" type="warning" effect="plain">未执行</el-tag>
        <el-tag v-else-if="scope.row.status === '2'" type="danger" effect="plain">拒绝</el-tag>
        <el-tag v-else-if="scope.row.status === '3'" type="success" effect="plain">已执行</el-tag>
      </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="ssubmittedmall-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-check"
            v-if="scope.row.status === '0'"
            @click="handleDetail(scope.row)"
            v-hasPermi="['hawk-eye:repair-work-order:edit']"
          >审批
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-if="scope.row.status === '2' || scope.row.status === '3'"
            @click="handleDetail(scope.row)"
            v-hasPermi="['hawk-eye:repair-work-order:edit']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            v-if="scope.row.status === '1'"
            @click="handleDetail(scope.row)"
            v-hasPermi="['hawk-eye:repair:edit']"
          >执行
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="color: red;"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hawk-eye:repair-work-order:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="Number(total)>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="1180px" append-to-body :close-on-click-modal="false">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="工单信息" name="problemPane">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="工单名称" prop="workOrderName">
                  <el-input v-model="form.workOrderName" :disabled="true"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="关联缺陷" prop="problemText">
                  <el-input v-model="form.problemText" placeholder="该脚本能够修复的缺陷,非必选项"
                            @focus="handleSelectAlarmLog"
                            :disabled="false">
                    <template slot="append">
                      <el-button @click="handleSelectAlarmLog" icon="el-icon-search"></el-button>
                    </template>
                  </el-input>
                </el-form-item>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="脚本名称" prop="repairApiName">
                  <el-input v-model="form.repairApiName" :disabled="true"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="功能描述" prop="repairDesc">
                  <el-input v-model="form.repairDesc" placeholder="请简要说明脚本用途、目的" type="textarea" maxlength="200"
                            :rows="2" show-word-limit :disabled="true"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="请求方式" prop="reqType">
                  <el-select
                    v-model="form.reqType"
                    placeholder="GET/POST"
                    :disabled="true"
                  >
                    <el-option
                      v-for="item in reqTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="请求地址" prop="reqUri">
                  <el-input v-model="form.reqUri" placeholder="请求地址格式:http://www.xxx.xx/xxx/xx?id=${id}&name=xxx"
                            :disabled="true">
                    <el-button slot="append" icon="el-icon-document-copy" v-clipboard="form.reqUri"
                               v-clipboard:success="copySuccessHandle"
                               v-clipboard:error="copyErrorHandle" :disabled="true"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="请求体" prop="reqBody">
                  <code-editor v-model="form.reqBody"
                               style="height: 190px;line-height: 1;pointer-events: none;opacity: 0.7;"
                               :aria-disabled="true"
                               :auto-format="true"
                               :smart-indent="true"
                               theme="dracula"
                               :indent-unit="4"
                               :line-wrap="false"
                               ref="codeEditor">
                  </code-editor>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="日志信息" name="alarmLogPane">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row :gutter="24" class="mb8">
              <el-col :span="18">
                <el-form-item label="链路ID" prop="traceId">
                  <el-input v-model="form.traceId" :disabled="true">
                    <el-button slot="append" icon="el-icon-document-copy" v-clipboard="form.traceId"
                               v-clipboard:success="copySuccessHandle"
                               v-clipboard:error="copyErrorHandle"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-button icon="el-icon-download" type="text" @click="exportTxt">导出日志信息</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="24" class="mb8">
              <el-col :span="6">
                <el-form-item label="服务名" prop="serviceName">
                  <el-input v-model="form.serviceName" :disabled="true" style="width:200px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="告警时间" prop="alarmTime">
                  <el-input v-model="form.alarmTime" :disabled="true" style="width:170px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="负责人" prop="chargeUserName">
                  <el-input v-model="form.chargeUserName" :disabled="true" style="width:130px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="告警标识" prop="stackHash">
                  <el-input v-model="form.stackHash" :disabled="true">
                  <el-button slot="append" icon="el-icon-document-copy" v-clipboard="form.stackHash"
                             v-clipboard:success="copySuccessHandle"
                             v-clipboard:error="copyErrorHandle"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" class="mb8">
              <el-col :span="12">
                <el-form-item label="代码文件" prop="errorFileName">
                  <el-input v-model="form.errorFileName" :disabled="true">
                    <el-button slot="append" icon="el-icon-document-copy" v-clipboard="form.errorFileName"
                               v-clipboard:success="copySuccessHandle"
                               v-clipboard:error="copyErrorHandle"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="请求地址" prop="requestUri">
                  <el-input v-model="form.requestUri" :disabled="true">
                    <el-button slot="append" icon="el-icon-document-copy" v-clipboard="form.requestUri"
                               v-clipboard:success="copySuccessHandle"
                               v-clipboard:error="copyErrorHandle"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" class="mb8">
              <el-col :span="24">
                <div style="height: 250px;overflow: auto;">
                  <json-viewer :value="form.logMessage == null ? {} :  form.logMessage"
                               :expand-depth=1
                               :expanded="true"
                               copyable
                               :boxed="false"></json-viewer>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.status === '1' || form.status === '3'"
                   icon="el-icon-caret-right" type="success" @click="executeRepairApi">
          {{execText}}
        </el-button>
        <el-button v-if="form.status === '0' || form.status === '2'" type="success" @click="approve">通 过</el-button>
        <el-button v-if="form.status === '0'" type="danger" @click="reject">拒 绝</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <problem-record-table ref="problemRecordTable" @submitted="handleSelectedProblem"/>
    <repair-params-table ref="repairParamsTable" @submitted="handleRefresh"/>
  </div>
</template>

<script>
  import {
    repairWorkOrderList,
    repairWorkOrderDetail,
    approveRepairWorkOrder,
    rejectRepairWorkOrder,
    removerRepairWorkOrder,
  } from "@/api/hawkeye/repairworkorder";

  import {CodeEditor} from "bin-code-editor"
  import ProblemRecordTable from "@/views/hawkeye/repair/modules/ProblemRecordTable";
  import RepairParamsTable from "@/views/hawkeye/repair/modules/RepairParamsTable";
  import JsonViewer from 'vue-json-viewer'

  export default {
    name: "RepairWorkOrder",
    components: {ProblemRecordTable, RepairParamsTable, CodeEditor, JsonViewer},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        repairWorkOrderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        disabled: false,
        execText: '执行',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          workOrderStatus: ['0', '1']
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        reqTypeOptions: [
          {
            label: "GET",
            value: 1
          }, {
            label: "POST",
            value: 2
          }
        ],
        statusOptions: [
          {
            label: "待审核",
            value: '0'
          }, {
            label: "未执行",
            value: '1'
          }, {
            label: "拒绝",
            value: '2'
          }, {
            label: "已执行",
            value: '3'
          }
        ],
        activeName: 'problemPane',
        storeStatusKey: 'hawkEye:repairworkorder:storeStatusKey',
      };
    },
    created() {
      this.initQueryParams();
      this.getList();
    },
    computed: {
      problemText: () => {
        return (rows) => {
          if (!rows || rows.length === 0) {
            return "";
          }
          return rows.length > 1 ? `${rows[0].problemName}等${rows.length}个缺陷` : rows[0].problemName;
        }
      }
    },
    methods: {
      /** 查询【请填写功能名称】列表 */
      getList() {
        this.loading = true;
        repairWorkOrderList(this.queryParams).then(res => {
          this.repairWorkOrderList = res.records || [];
          this.total = res.total;
        }).finally(() => {
          this.loading = false;
        });
      },
      initQueryParams() {
        let statusAsString = localStorage.getItem(this.storeStatusKey);
        if (statusAsString) {
          try {
            this.$set(this.queryParams, 'workOrderStatus', JSON.parse(statusAsString))
          } catch (e) {
            localStorage.removeItem(this.storeStatusKey);
          }
        }
      },
      handleStoreQueryParams(key, value) {
        if (value) {
          localStorage.setItem(key, JSON.stringify(value));
        } else {
          localStorage.removeItem(key);
        }
      },
      handleLogLabel(row) {
        let stackHash = row.workOrderName.substring(row.workOrderName.lastIndexOf("[")+1 , row.workOrderName.lastIndexOf("]"))
        this.$router.push({
          path: '/hawkeye/alarmlog',
          query: {
            stackHash: stackHash
          }
        })
      },
      handleRepairLabel(row) {
        this.$router.push({
          path: '/hawkeye/repair',
          query: {
            repairApiName: row.repairApiName
          }
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          traceId: null,
          workOrderName: null,
          repairApiName: null,
          stackHash: null
        };
        this.resetForm("form");
        this.disabled = false;
        this.execText = '执行';
      },
      handleClick(tab, event) {

      },
      exportTxt() {
        this.download('/hawk-eye/log/export-log-txt?baseAlarmId=' + this.form.baseAlarmId, {}, `告警日志_${new Date().getTime()}.txt`)
      },
      executeRepairApi() {
        this.$modal.confirm('确认执行该修复脚本吗？').then(() => {
          this.$refs.repairParamsTable.open(this.form.repairApiId, this.form.reqType, true, this.form.id);
        })
      },
      handleRefresh() {
        this.$refs.repairParamsTable.cancel();
        this.cancel();
        this.getList();
      },
      handleSelectAlarmLog() {
        this.$refs.problemRecordTable.open(this.form.repairApiId, true);
      },
      // 复制成功回调函数
      copySuccessHandle(value) {
        this.$modal.msgSuccess("内容已复制到剪切板,可进行粘贴");
      },
      // 复制失败回调函数
      copyErrorHandle(value) {
        this.$modal.msgError("复制失败,请确认浏览器支持复制功能");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        localStorage.removeItem(this.storeStatusKey);
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleDetail(row) {
        this.reset();
        const id = row.id || this.ids
        repairWorkOrderDetail(id).then(res => {
          let data = res.data;
          data.serviceName = `${data.serviceCnName ? data.serviceCnName : 'unknown'}(${data.serviceZnName ? data.serviceZnName : 'unknown'})`;
          this.form = data;
          this.$set(this.form, 'problemText', this.problemText(data.problemList));
          this.title = "审批";
          if (row.status === '3') {
            this.disabled = true;
            this.execText = '重新执行';
            this.title = "查看";
          }
          if (row.status === '1') {
            this.title = "执行";
            this.execText = '执行';
          }
          this.open = true;
        });
      },
      handleSelectedProblem(rows) {
        this.$set(this.form, 'problemText', this.problemText(rows))
        this.$set(this.form, 'problemList', rows || [])
      },
      /** 提交按钮 */
      approve() {
        this.$modal.confirm('是否确认通过（通过后需要手动执行脚本）？').then(() => {
          return approveRepairWorkOrder(this.form);
        }).then(() => {
          this.$modal.msgSuccess("操作完成");
          let row = {id: this.form.id};
          this.handleDetail(row);
          this.getList();
        }).catch(() => {
        });
      },
      reject() {
        this.$modal.confirm('是否确认拒绝（拒绝后仍然可以撤回）？').then(() => {
          return rejectRepairWorkOrder(this.form);
        }).then(() => {
          this.$modal.msgSuccess("操作完成");
          this.open = false;
          this.getList();
        }).catch(() => {
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除数据？').then(function () {
          return removerRepairWorkOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      handleDoc() {
        let url = 'https://www.wolai.com/toMMNcCE57J9teqJd8W4zb';
        if (!url) {
          return;
        }
        window.open(url);
      }
    }
  };
</script>
